package com.yuanxiao.common.api.base;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.yuanxiao.common.api.constant.UsedType;
import com.yuanxiao.common.api.entity.SysDeptEntity;
import com.yuanxiao.common.api.entity.SysDeptExtendInfoEntity;
import com.yuanxiao.common.api.entity.SysUserEntity;
import com.yuanxiao.common.api.feign.SysServerFeignClient;
import com.yuanxiao.common.api.service.FeignBaseService;
import com.yuanxiao.common.core.constant.GlobalConstants;
import com.yuanxiao.common.core.exception.RRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yuanxiao.common.api.entity.dto.SysUserAuthDTO;
import com.yuanxiao.common.core.result.R;
import com.yuanxiao.common.core.result.ResultCode;
import com.yuanxiao.common.web.util.JwtUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Manager Controller 公共组件
 */
public abstract class ManagerBaseController {
    protected Logger logger = LoggerFactory.getLogger (getClass ());

    protected SysUserAuthDTO getUser() {
        return JSONUtil.toBean (JwtUtils.getUserInfoJSON (), SysUserAuthDTO.class);
    }

    protected SysDeptEntity getDeptInfo() {
        return getUser ().getDeptInfo ();
    }

    protected Long getUserId() {
        return getUser ().getId ();
    }

    protected Long getRoleId() {
        return getUser ().getRoleId ();
    }

    protected Long getDeptId() {
        Long deptId = getUser ().getDeptId ();
        return deptId != null ? getUser ().getDeptId () : -1000;
    }

    protected SysDeptEntity getRootDept() {
        SysDeptEntity root = new SysDeptEntity ();
        root.setId (0L);
        root.setTenantId(-1L);
        root.setTenantName ("运维平台");
        root.setName ("平台[一级部门]");
        root.setDeptId (GlobalConstants.ROOT_ROOT_ID);
        root.setDeptIds (",0,");
        root.setOpen (true);
        root.setLevel (0);
        return root;
    }

    protected boolean judgeDataAuthorityAboutDeptIdArgs(String deptIds) {
        boolean bool = false;
        String[] deptIdArray = deptIds.split (",");
        bool = Arrays.asList (deptIdArray).contains (getDeptId () + "");
        return bool;
    }

    protected R judgeDataAuthorityAboutUserId(SysServerFeignClient sysServerFeignClient, long userId) {
        R userResult = sysServerFeignClient.getUserByUserId (userId);
        if (userResult.getData () == null) {
            return  R.failed (ResultCode.USER_NOT_EXIST.getMsg ());
        }

        //SysUserEntity sysUserEntity = JSON.parseObject (JSON.toJSONString (userResult.getData ()), SysUserEntity.class);
        SysUserEntity sysUserEntity = JSONUtil.toBean (JSONUtil.toJsonStr (userResult.getData ()), SysUserEntity.class);
        if(!judgeDataAuthorityAboutDeptIdArgs (sysUserEntity.getDeptIds ())){
            return R.failed (ResultCode.AUTHORIZED_ERROR);
        }
        return R.returnDataWrapper (sysUserEntity);
    }


    protected Long getDeptTradeCode() {
        return getDeptExtendInfo ().getDicTradeCode ();
    }

    protected boolean judgeDataAuthorityAboutTradeCode(Long tradeCode) {
        if (getDeptTradeCode ().longValue () == 0) {
            return true;
        }
        return getDeptTradeCode ().longValue () == tradeCode.longValue ();
    }


    protected SysDeptExtendInfoEntity getDeptExtendInfo() {
        SysDeptEntity deptEntity = getUser ().getDeptInfo ();
        if (deptEntity.getExtendInfo () == null && deptEntity.getLevel ().longValue () <= 1) {
            return getDefaultDeptExtendInfo ();
        }
        return deptEntity.getExtendInfo ();
    }

    protected SysDeptExtendInfoEntity getDefaultDeptExtendInfo() {
        SysDeptExtendInfoEntity defaultInfo = new SysDeptExtendInfoEntity ();
        defaultInfo.setId (0L);
        defaultInfo.setDicTradeCode (0l);
        defaultInfo.setDicTradeCodes (",0,");
        defaultInfo.setType ("sys");
        defaultInfo.setTradeType ("direct");
        return defaultInfo;
    }
    protected R getDeptByArgsDeptId (SysServerFeignClient sysServerFeignClient, Long deptId) {
        SysDeptEntity deptEntity = null;
        if (deptId.longValue () == 0) {
            deptEntity = getRootDept ();
        } else {
            R deptResult = sysServerFeignClient.getDeptById (deptId);
            if (deptResult.get ("dept") == null) {
                return  R.failed ("参数错误");
            }
            // deptEntity = JSON.parseObject (JSON.toJSONString (deptResult.getData ()), SysDeptEntity.class);
            deptEntity = JSONUtil.toBean (JSONUtil.toJsonStr (deptResult.get("dept")), SysDeptEntity.class);
        }
        if (!judgeDataAuthorityAboutDeptIdArgs (deptEntity.getDeptIds ())) {
            return R.failed (ResultCode.AUTHORIZED_ERROR);
        }
        return R.returnDataWrapper (deptEntity);
    }

    protected String getThisYearMonth () {
        int month = (DateUtil.thisMonth() + 1);
        String monthStr = month<10 ? String.format ("0%s", month) : month+"";
        return String.format ("%s-%s", DateUtil.thisYear (), monthStr);
    }

    protected Object[] monthArr (int year, int month) {
        int maxDay = DateUtil.lengthOfMonth (month, DateUtil.isLeapYear(year));
        List arr = new ArrayList ();
        String monthStr = month<10 ? String.format ("0%s", month) : month+"";
        String dayStr = "";
        for (int i=1; i<=maxDay; i++) {
            dayStr = i<10 ? String.format ("0%s", i) : i+"";
            arr.add (String.format ("%s-%s", monthStr, dayStr));
        }
        return arr.toArray ();
    }

    protected R judgeArgsByFeign(FeignBaseService feignBaseService, UsedType usedType, String serverCode, String bizCode, Object bodyArgs, Object pathArgs) {
        return feignBaseService.feignCall(serverCode, usedType, bizCode, bodyArgs, pathArgs);
    }
    protected Long getTenantId() {
        Long tenantId = this.getUser().getDeptInfo().getTenantId();
        if (tenantId == null) {
            throw new RRException ("账号归属错误，请联系管理员");
        }
        if (tenantId == -1L) {
            throw new RRException ("请选择您要维护的平台");
        }
        return tenantId;
    }

    protected boolean judgeDataAuthorityAboutTenantId(Long tenantId) {
        if (tenantId == null) {
            throw new RRException("平台参数错误");
        }
        Long currentTenantId = this.getUser().getDeptInfo().getTenantId();
        if (currentTenantId == null) {
            throw new RRException ("账号归属错误，请联系管理员");
        }
        if (currentTenantId == -1L) {
            return true;
        }
        boolean bool = tenantId.equals(currentTenantId);
        if (!bool) {
            throw new RRException ("无权限操作当前平台数据");
        } else {
            return bool;
        }
    }

    /**
     * 获取业务部门信息
     */
    protected R getBizDept(SysServerFeignClient sysServerFeignClient, long deptId) {
        R rt = this.getDeptByArgsDeptId (sysServerFeignClient, deptId);
        if (!"0".equals (rt.getCode ())) {
            return rt;
        }
        // R deptResult = sysServerFeignClient.getDeptById(entity.getDeptId ());
        SysDeptEntity deptEntity = JSONUtil.toBean(JSONUtil.toJsonStr(rt.getData()), SysDeptEntity.class);
        return R.returnDataWrapper (deptEntity);
    }

    /**
     * 获取业务部门信息
     * @param sysServerFeignClient
     * @param deptId
     * @return
     */
    protected SysDeptEntity getDeptInfo(SysServerFeignClient sysServerFeignClient, Long deptId){
        R r = sysServerFeignClient.getDeptById(deptId);
        if (!"0".equals(r.getCode())){
            return new SysDeptEntity();
        }
        return JSONUtil.toBean(JSONUtil.toJsonStr(r.get("dept")), SysDeptEntity.class);
    }
}
